<template>
    <el-row class="contain-box">
        <site-nav/>
        <div class="view-body">
            <el-row>
                <el-form class="inline-form" inline>
                    <el-form-item v-if="showBackButton">
                        <el-button @click="$router.go(-1)"><i class="el-icon-arrow-left el-icon--left"/>返回
                        </el-button>
                    </el-form-item>
                    <el-form-item v-if="!hiddenAppSelect" label="应用">
                        <el-select clearable filterable placeholder="请选择" v-model="params.appId">
                            <el-option value="" label="不限"/>
                            <el-option v-for="item in apps" :key="item.appId"
                                       :value="item.appId" :label="getWxAppDisplayName(item)">
                                {{getWxAppDisplayName(item)}}
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="openId">
                        <el-input @clear="search" clearable placeholder="请输入openId" v-model="params.openId"/>
                    </el-form-item>
                    <el-form-item label="unionId">
                        <el-input @clear="search" clearable placeholder="请输入unionId" v-model="params.unionId"/>
                    </el-form-item>
                    <el-form-item label="昵称">
                        <el-input @clear="search" clearable placeholder="请输入昵称" v-model="params.nickNameLike"/>
                    </el-form-item>
                    <el-form-item label="标签">
                        <el-select clearable filterable placeholder="请选择" v-model="params.tagId">
                            <el-option value="" label="不限"/>
                            <el-option v-for="item in tags" :key="item.tagId"
                                       :value="item.tagId" :label="item.tagName"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="激活">
                        <el-select clearable filterable placeholder="请选择" v-model="params.activated">
                            <el-option value="" label="不限"/>
                            <el-option :value="true" label="是"/>
                            <el-option :value="false" label="否"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="注册时间">
                        <el-date-picker
                                v-model="registryTimes"
                                type="datetimerange"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                @clear="search"
                                @change="search"
                        />
                    </el-form-item>
                    <el-form-item label="最后登录时间">
                        <el-date-picker
                                v-model="lastLoginTimes"
                                type="datetimerange"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                @clear="search"
                                @change="search"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="search" icon="el-icon-search" type="primary">搜索</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="exportExcel">导出Excel</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-form class="inline-form" inline>
                    <el-form-item>
                        <el-button @click="setTagsByUsers" :disabled="openIds.length <= 0" type="primary">设置标签</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-col>
                    <el-table :data="list" border size="small" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55"/>
                        <el-table-column align="center" label="openId" prop="openId"/>
                        <el-table-column align="center" label="unionId" prop="unionId"/>
                        <el-table-column align="center" label="昵称" prop="nickName"/>
                        <el-table-column align="center" label="头像" width="80">
                            <template slot-scope="scope">
                                <el-avatar shape="square" :src="scope.row.avatarUrl"/>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="应用" width="200" v-if="!hiddenAppSelect">
                            <template slot-scope="scope">
                                <span>{{scope.row.appName}}</span>
                                <br>
                                <span>({{scope.row.appId}})</span>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="注册时间" width="90">
                            <template slot-scope="scope">
                                <p class="date-time">{{scope.row.registryTime | dateFormat}}</p>
                                <p class="date-time">{{scope.row.registryTime | timeFormat}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="最后登录时间" width="100">
                            <template slot-scope="scope">
                                <p class="date-time">{{scope.row.lastLoginTime | dateFormat}}</p>
                                <p class="date-time">{{scope.row.lastLoginTime | timeFormat}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="激活用户" width="80">
                            <template slot-scope="scope">
                                <commons-enable :value="scope.row.activated"/>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="标签">
                            <template slot-scope="scope">
                                <span class="tag" v-for="tag in scope.row.tags" :key="tag.tagId">{{tag.tagName}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="260">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="viewLoginLogs(scope.row)">登录记录</el-button>
                                <el-button size="mini" @click="setTagsByUser(scope.row)">设置标签</el-button>
                                <el-button size="mini" type="danger" @click="deleteEntity(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <el-row>
                <el-col class="pagination">
                    <el-pagination :current-page="params.pageId" :page-size="params.pageSize" :total="count"
                                   @current-change="currentChange" background layout="total, prev, pager, next"/>
                </el-col>
            </el-row>
        </div>

        <el-dialog :before-close="dialogClose" title="设置标签" :visible.sync="dialog.show"
                   class="dialog">
            <el-form label-width="120px" ref="form" size="small">
                <el-form-item label="选择标签">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="selectAll" @change="selectAllHandler">全选
                    </el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="selectedTagIds" @change="checkedTagsChangeHandler">
                        <el-checkbox v-for="tag in tags" :label="tag.tagId" :key="tag.tagId">{{tag.tagName}}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="dialogClose" size="mini">取 消</el-button>
                <el-button :loading="dialog.submitting" @click="dialogSubmit" size="mini" type="primary">确 定</el-button>
            </div>
        </el-dialog>
    </el-row>
</template>
<script lang="ts">
  import {ID, PARAMS} from '@/api/http';
  import SetTagRequest from '@/modules/weChat/structure/setTagRequest';
  import DialogInfo from '@/structure/dialogInfo';
  import download from '@/utils/download';
  import {Component, Vue} from 'vue-property-decorator';
  import UserTagApi from '../../api/userTagApi';
  import WxAppApi from '../../api/wxAppApi';
  import Api from '../../api/wxUserApi';
  import UserTag from '../../structure/userTag';
  import WxApp from '../../structure/wxApp';
  import {WxAppTypeMap} from '../../structure/wxAppType';
  import Entity from '../../structure/wxUser';

  @Component
  export default class Page extends Vue {
    public showBackButton: boolean = false;
    public hiddenAppSelect: boolean = false;
    public wxAppTypeMap = WxAppTypeMap;
    public list: Entity[] = [];
    public apps: WxApp[] = [];
    public tags: UserTag[] = [];
    public count: number | null = null;
    public params: PARAMS = {
      pageId: 1,
      appId: '',
      openId: '',
      unionId: '',
      nickNameLike: null,
      activated: '',
      tagId: '',
      queryTags: true
    };
    public registryTimes: Date[] = [];
    public lastLoginTimes: Date[] = [];
    public dialog: DialogInfo = new DialogInfo();
    public isIndeterminate: boolean = false;
    public selectAll: boolean = false;
    public selectedTagIds: ID[] = [];
    public multiUser: boolean = false;
    public openId: string = '';
    public openIds: string[] = [];
    public submittingTags: boolean = false;

    public created(): void {
      this.showBackButton = this.$route.query.showBackButton === 'true';
      this.hiddenAppSelect = this.$route.query.hiddenAppSelect === 'true';
      this.$parseParams(this.params, this.$route);
      WxAppApi.all().then((res) => this.apps = res);
      UserTagApi.all().then((res) => this.tags = res);
      this.getDataList();
    }

    public handleSelectionChange(list: Entity[]): void {
      this.openIds = list.map((e) => e.openId);
    }

    public setTagsByUsers(): void {
      this.selectedTagIds = [];
      this.multiUser = true;
      this.openSelectTagDialog();
    }

    public setTagsByUser(info: Entity): void {
      this.openId = info.openId;
      this.selectedTagIds = info.tagIds;
      this.multiUser = false;
      this.openSelectTagDialog();
    }

    public selectAllHandler(all: boolean) {
      this.selectedTagIds = all ? this.tags.map((e) => e.tagId) : [];
      this.isIndeterminate = false;
    }

    public checkedTagsChangeHandler(val: any) {
      const selectNumber = val.length;
      this.selectAll = selectNumber === this.tags.length;
      this.isIndeterminate = selectNumber > 0 && selectNumber < this.tags.length;
    }

    public openSelectTagDialog(): void {
      this.dialog.show = true;
      this.isIndeterminate = this.selectedTagIds.length > 0 && this.selectedTagIds.length < this.tags.length;
    }

    public dialogClose(): void {
      this.dialog.show = false;
      this.selectedTagIds = [];
      this.openId = '';
      this.openIds = [];
    }

    public dialogSubmit(): void {
      if (this.submittingTags) {
        return;
      }

      this.submittingTags = true;

      const request: SetTagRequest = new SetTagRequest();
      request.tagIds = this.selectedTagIds;
      if (this.multiUser) {
        request.openIds = this.openIds;
        Api.batchSetTags(request).then(() => {
          this.$message.success('标签设置成功');
          this.submittingTags = false;
          this.getDataList();
          this.dialogClose();
        }).catch(() => {
          this.submittingTags = false;
        });
      } else {
        Api.setTags(this.openId, request).then(() => {
          this.$message.success('标签设置成功');
          this.submittingTags = false;
          this.getDataList();
          this.dialogClose();
        }).catch(() => {
          this.submittingTags = false;
        });
      }
    }

    public getWxAppDisplayName(item: WxApp): string {
      return `${item.appName}(${item.appId}) - ${this.wxAppTypeMap[item.wxAppType]}`;
    }

    public getDataList(): void {
      Api.findList(this.getParams()).then((res) => {
        this.list = res.list;
        this.count = res.count;
      });
    }

    public getParams() {
      const params = {...this.params};

      if (this.registryTimes && this.registryTimes.length) {
        params.registryTimeStartWith = this.registryTimes[0];
        params.registryTimeEndWith = this.registryTimes[1];
      }
      if (this.lastLoginTimes && this.lastLoginTimes.length) {
        params.lastLoginTimeStartWith = this.lastLoginTimes[0];
        params.lastLoginTimeEndWith = this.lastLoginTimes[1];
      }
      return params;
    }

    public search(): void {
      this.currentChange(1);
    }

    public currentChange(val: number): void {
      this.params.pageId = val;
      this.getDataList();
    }

    public deleteEntity(info: Entity): void {
      this.$confirm('是否删除该用户?', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Api.delete(info.appId, info.openId).then(() => {
          this.getDataList();
          this.$message.success('删除成功!');
        });
      });
    }

    public viewLoginLogs(info: Entity): void {
      this.$router.push({
        name: 'WeChat_LoginLog',
        query: {
          appId: info.appId,
          openId: info.openId
        }
      });
    }

    public exportExcel(): void {
      Api.exportExcel(this.getParams()).then((blob) => {
        download(blob, '微信用户列表 ' + this.$moment(Date.now()).format('YYYY-MM-DD-HH-mm-ss') + '.xlsx');
      });
    }
  }
</script>
<style lang="scss" scoped>
    .tag {
        &:after {
            content: '、';
        }
        &:last-child:after {
            content: '';
        }
    }
</style>
